package com.liull.netty.itcast.nio.bytebuffer;

import java.nio.ByteBuffer;

/**
 * @Author: liull
 * @Description: 纠正 半包 粘包问题
 * @Date: Created in 23:51 2021/7/21
 * @Modified By:
 */
public class PacketCorrectTest {
    public static void main(String[] args) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(32);
        byteBuffer.put("Hello,world\nI'm liudaye\nHo".getBytes());
        split(byteBuffer);
        byteBuffer.put("w are you?\n".getBytes());
        split(byteBuffer);
    }

    private static void split(ByteBuffer source) {
        // 切换为读模式
        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            if (source.get(i) == '\n') {
                int length = i + 1 - source.position();
                ByteBuffer target = ByteBuffer.allocate(length);
                // source读 写入target
                for (int j = 0; j < length; j++) {
                    byte b = source.get();
                    target.put(b);
                }
                // 切换为读模式
                target.flip();
                ByteBufferUtil.printDesc(target);

            }
        }
        source.compact();
    }
}
